package com.ltmall.api.controller;

import com.google.gson.Gson;
import com.ltmall.api.bean.*;
import com.ltmall.api.comm.Path;
import com.ltmall.api.entity.JsonCrazy;
import com.ltmall.api.entity.JsonCrazyCard;
import com.ltmall.api.entity.JsonCrazyCardWinner;
import com.ltmall.api.manager.AccountManager;
import com.ltmall.api.manager.CrazyManager;
import com.ltmall.api.manager.OrderManager;
import com.ltmall.api.parse.CrazyCompetitionMemberParse;
import com.ltmall.api.parse.bean.CompetitionMember;
import com.ltmall.api.util.RemoteUtil;
import com.ltmall.api.weixin.pay.Constants;
import com.ltmall.api.weixin.pay.utils.WeixinUtils;
import com.ltmall.api.weixin.pay.utils.WeixinUtils.WXPayType;
import com.ltmall.api.weixin.tecent.comm.RandomStringGenerator;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

// import com.ali.dayu.MSGManager;

@Controller
public class CrazyController {

    private CrazyManager crazyManager;
    private AccountManager accountManager;
    private OrderManager orderManager;

    public OrderManager getOrderManager() {
        return orderManager;
    }

    public void setOrderManager(OrderManager orderManager) {
        this.orderManager = orderManager;
    }

    public AccountManager getAccountManager() {
        return accountManager;
    }

    public void setAccountManager(AccountManager accountManager) {
        this.accountManager = accountManager;
    }

    public CrazyManager getCrazyManager() {
        return crazyManager;
    }

    public void setCrazyManager(CrazyManager crazyManager) {
        this.crazyManager = crazyManager;
    }

    // 加入疯抢
    public void join(HttpServletRequest request, HttpServletResponse response) {
        CrazyCompetitionMember member = (CrazyCompetitionMember) RemoteUtil.request(request,
                new CrazyCompetitionMember());
        String ip = request.getParameter("ip");

        String userPhone = accountManager.getAccount(null, member.getUserID()).getPhone();
        /*
         * 判断疯抢的人数是否能达到 人数达到出结果 人数达不到显示列表
         */
        member.setUserPhone(userPhone);
        member.setStation(0);

        List<CrazyCompetitionMember> memberList = crazyManager.getCompetitionMember(member.getPhase(),
                member.getGiftCardID(), 0);
        WalletGiftCard card = crazyManager.getCard(member.getGiftCardID());

        int memberChance = 0;
        for (CrazyCompetitionMember mm : memberList) {
            memberChance += mm.getChance();
        }

        if (memberChance + member.getChance() > card.getMoney()) {
            RemoteUtil.response(response, null, -1, "操作失败");
            return;
        }

        crazyManager.addMember(member);
        // 总价格
        int totalPrice = (int) (member.getChance() * 100);
        // 一元夺宝body
        String body = "乡味汇订单";

        // 交易号
        String out_trade_no = WeixinUtils.getOut_trade_no();
        int fakeTotalPrice = 1;

        TradeNo no = generateTradeNo(out_trade_no, member.getNumber() + "", member.getUserID());
        // 插入交易号
        orderManager.addTradeNo(no);

        // 生成支付
        pay(totalPrice, body, ip, out_trade_no, request, response);
    }

    public void pay(int totalPrice, String body, String ip, String out_trade_no, HttpServletRequest request,
                    HttpServletResponse response) {
        System.out.println("----创建预付定单-----");
        try {
            System.out.println("totalPrice--->" + totalPrice);
            System.out.println("product_name--->" + body);
            System.out.println("ip--->" + ip);
            /*
             * 调用统一支付接口
             */
            String notifyUrl = Path.weixin_pay_notifyurl_crazy;

            Map<String, String> map = WeixinUtils.payUnifiedorder(WXPayType.AppPay, body, totalPrice, ip, out_trade_no,
                    notifyUrl, null);
            TreeMap<String, String> outParams = new TreeMap<String, String>();
            if (null != map) {
                String app_id = map.get("appid");
                /*
                 * 获取预支付ID
                 */
                String prepayid = map.get("prepay_id");
                /*
                 * 创建预支付sign签名
                 */
                String noceStr = RandomStringGenerator.getRandomStringByLength(32);
                String timeStamp = String.valueOf((System.currentTimeMillis() / 1000));
                List<NameValuePair> signParams = new LinkedList<NameValuePair>();
                signParams.add(new BasicNameValuePair("appid", app_id));
                signParams.add(new BasicNameValuePair("noncestr", noceStr));
                signParams.add(new BasicNameValuePair("package", "Sign=WXPay"));
                signParams.add(new BasicNameValuePair("partnerid", Constants.MCH_ID));
                signParams.add(new BasicNameValuePair("prepayid", prepayid));
                signParams.add(new BasicNameValuePair("timestamp", timeStamp));

                String sign = WeixinUtils.genSign(signParams);

                /**
                 * 返回手机端支付需要的全部参数
                 */
                outParams.put("retcode", "0");
                outParams.put("retmsg", "OK");
                outParams.put("appid", Constants.APP_ID);
                outParams.put("noncestr", noceStr);
                outParams.put("partnerid", Constants.MCH_ID);
                outParams.put("package", "Sign=WXPay");
                outParams.put("prepayid", prepayid);
                outParams.put("out_trade_no", out_trade_no);
                outParams.put("timestamp", timeStamp);
                outParams.put("sign", sign);

                String param = "&number=" + out_trade_no;
                outParams.put("aliPayNotifyUrl", Path.ali_pay_notifyurl_crazy + param);
            } else {
                outParams.put("retcode", "-1");
                outParams.put("retmsg", "错误：获取不到Token");
            }

            Gson gson = new Gson();
            RemoteUtil.response(response, gson.toJson(outParams), 1, "返回成功");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 阿里通知
    public void aliNotify(HttpServletRequest request, HttpServletResponse response) {
        String tradeNO = request.getParameter("number");
        /*
         * 提交之后判断有没有中奖者 有中奖者修改本期状态为结束状态
         */

        TradeNo trade = orderManager.getTradeNo(tradeNO);
        CrazyCompetitionMember member = crazyManager.getCompetitionMember(Integer.parseInt(trade.getOrderIDs()));
        if (member == null || member.getStation() == 1) {
            return;
        }
        // 修改中奖者number
        updateCardWinner(member.getGiftCardID(), member.getPhase(), member.getNumber());
    }

    // 获取交易号
    public TradeNo generateTradeNo(String no, String orderIDs, int userID) {
        TradeNo tNo = new TradeNo();
        tNo.setTradeNo(no);
        tNo.setOrderIDs(orderIDs);
        tNo.setUserID(userID);
        return tNo;
    }

    ;

    // 微信通知
    @SuppressWarnings("unchecked")
    public void wxNotify(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("-------微信通知来了---------");
        InputStream inputStream = null;
        Map<String, String> map = null;
        try {
            // 解析结果存储在HashMap
            map = new HashMap<String, String>();
            inputStream = request.getInputStream();
            // 读取输入流
            SAXReader reader = new SAXReader();
            Document document = reader.read(inputStream);
            // 得到xml根元素
            Element root = document.getRootElement();
            // 得到根元素的所有子节点
            List<Element> elementList = root.elements();
            // 遍历所有子节点
            for (Element e : elementList)
                map.put(e.getName(), e.getText());
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            // 释放资源
            try {
                if (inputStream != null) {
                    inputStream.close();
                    inputStream = null;
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        /*
         * map处理
         */
        if ("SUCCESS".equals(map.get("return_code"))) {
            // 这个tradeNo就是giftCardID
            String tradeNO = map.get("out_trade_no");
            /*
             * 提交之后判断有没有中奖者 有中奖者修改本期状态为结束状态
             */
            TradeNo trade = orderManager.getTradeNo(tradeNO);
            CrazyCompetitionMember member = crazyManager.getCompetitionMember(Integer.parseInt(trade.getOrderIDs()));
            // 修改member的状态
            if (member == null || member.getStation() == 1) {
                return;
            }
            // 修改中奖者number
            updateCardWinner(member.getGiftCardID(), member.getPhase(), member.getNumber());
            /*
             * 操作成功，返回微信SUCCESS
             */
            response.resetBuffer();
            response.setContentType("text/xml; charset=UTF-8");
            String returnXml = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";

            PrintWriter writer;
            try {
                writer = response.getWriter();
                writer.print(returnXml);
                writer.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    // public void updatePhaseStation(int phase) {
    // CrazyCompetition comp = crazyManager.getCompetition(phase);
    // String winners = comp.getWinnersID();
    // String winnersArr[] = winners.split(";");
    //
    // boolean tag = true;
    // for (String winner : winnersArr) {
    // if (winner.equals("0")) {// 存在未中奖的卡号
    // tag = false;
    // break;
    // }
    // }
    // if (tag) {
    // // 修改活动状态
    // crazyManager.updatePhaseStation(0, phase);
    // }
    // };

    // 人数满了修改中奖者
    public void updateCardWinner(int cardID, int phase, int number) {
        WalletGiftCard card = crazyManager.getCard(cardID);

        int station = 1;// 表示已经支付
        crazyManager.updateMemberStation(number, station);
        List<CrazyCompetitionMember> list = crazyManager.getCompetitionMember(phase, cardID, 1);

        int allMember = 0;
        for (CrazyCompetitionMember member : list) {
            allMember += member.getChance(); // 所有的人数
        }

        if (allMember >= card.getMoney()) {// 表示可以开奖了
            // 获取此次疯抢的状态
            CrazyCompetition comp = crazyManager.getCompetition(phase);
            int winnerID = autoWinner(list, phase, cardID, card.getActivationCode());

            String cardIDs = comp.getGiftCardID();
            String userIDs = comp.getWinnersID();

            String cardIDArr[] = cardIDs.split(";");
            String userIDArr[] = userIDs.split(";");

            StringBuffer winnerBuffer = new StringBuffer();
            for (int i = 0; i < cardIDArr.length; i++) {
                if (cardIDArr[i].equals(cardID + "")) {
                    winnerBuffer.append(winnerID).append(";");
                } else {
                    winnerBuffer.append(userIDArr[i]).append(";");
                }
            }

            String w = winnerBuffer.toString();
            w = w.substring(0, w.length() - 1);// 去除最后一个分号

            crazyManager.updateWinner(phase, comp.getGiftCardID(), w);
        }
    }

    // 中奖者
    public void cardWinner(HttpServletRequest request, HttpServletResponse response) {
        String phase = request.getParameter("phase");
        String cardID = request.getParameter("cardID");
        CrazyCompetition cc = crazyManager.getCompetition(Integer.parseInt(phase));

        String cardIDs = cc.getGiftCardID();
        String userIDs = cc.getWinnersID();

        String cardIDArr[] = cardIDs.split(";");
        String userIDArr[] = userIDs.split(";");

        String winnerID = null;
        for (int i = 0; i < cardIDArr.length; i++) {
            if (cardIDArr[i].equals(cardID)) {
                winnerID = userIDArr[i];
            }
        }
        if (winnerID == null) {
            RemoteUtil.response(response, null, -1, "返回失败");
            return;
        }

        CrazyCompetitionMember winMem = crazyManager.getCompetitionMember(Integer.parseInt(winnerID));
        int winnerUserID = winMem.getUserID();
        ClientInfo info = accountManager.getInfo(winnerUserID);

        int time = 0;
        String luckyNumber = "";
        int chance = 0;

        List<CrazyCompetitionMember> memberWinner = crazyManager.getOneCompetitionMember(Integer.parseInt(cardID),
                winnerUserID);

        List<CrazyCompetitionMember> member = crazyManager.getCompetitionMember(Integer.parseInt(phase),
                Integer.parseInt(cardID), 0);

        for (CrazyCompetitionMember cc1 : memberWinner) {
            time += cc1.getChance();
            if (cc1.getChance() > chance) {
                luckyNumber = cc1.getNumber() + "";
                chance = cc1.getChance();
            }
        }
        JsonCrazyCardWinner winner = new JsonCrazyCardWinner();
        winner.setWinnerName(info.getName());
        winner.setCardID(Integer.parseInt(cardID));
        winner.setWinnerPhoto(Path.nginx_server_dir_client + Path.PHOTO + File.separator + info.getPhoto());
        winner.setMemberList(member);
        winner.setWinnerPhone(memberWinner.get(0).getUserPhone());
        winner.setLuckyNumber(luckyNumber);
        winner.setTime(time + "");
        RemoteUtil.response(response, winner, 1, "返回成功");
    }

    // 修改礼品卡的userID和发送短信
    public void updateGiftCardUserID(int userID, int cardID) {
        crazyManager.updateGiftCardID(userID, cardID);// 修改卡号和userID
    }

    // 发送短信
    public void sendMessage(String phone, String cardNumber, String code) {
        // MSGManager.activeMSG(phone, cardNumber, code);
    }

    // 自动中奖者
    public int autoWinner(List<CrazyCompetitionMember> list, int phase, int giftCardID, String code) {
        List<Integer> numberList = new ArrayList<Integer>();
        // 将所有的机会按照列表显示出来
        for (CrazyCompetitionMember ccm : list) {
            int chance = ccm.getChance();// 获取最多的机会
            int number = ccm.getNumber();
            for (int i = 1; i <= chance; i++) {
                numberList.add(number);
            }
        }

        Random rand = new Random();
        int randNum = rand.nextInt(numberList.size());
        int number = numberList.get(randNum);

        CrazyCompetitionMember member = crazyManager.getCompetitionMember(number);
        // 修改礼品卡的userID
        updateGiftCardUserID(member.getUserID(), giftCardID);
        // 发送消息
        sendMessage(member.getUserPhone(), giftCardID + "", code);
        return member.getNumber();
    }

    // 当前疯抢
    public void todayCard(HttpServletRequest request, HttpServletResponse response) {
        int maxPhase = crazyManager.maxPhase();
        if (maxPhase == 0) {
            RemoteUtil.response(response, null, 0, "无数据");
            return;
        }

        CrazyCompetition competition = crazyManager.getCompetition(maxPhase);
        String cardIDs = competition.getGiftCardID();
        String userIDs = competition.getWinnersID();

        String[] cardIDArr = cardIDs.split(";");
        String[] userIDArr = userIDs.split(";");

        List<JsonCrazy> list = new ArrayList<>();
        for (int i = 0; i < cardIDArr.length; i++) {
            int cardID = Integer.parseInt(cardIDArr[i]);
            int winnerID = Integer.parseInt(userIDArr[i]);
            int station = 0;
            if (winnerID != 0) {
                // 进行中
                station = 1;
            }

            int joinMember = 0;
            List<CrazyCompetitionMember> memberList = crazyManager.getCompetitionMember(maxPhase, cardID, 0);
            for (CrazyCompetitionMember member : memberList) {
                joinMember += member.getChance();
            }

            WalletGiftCard card = crazyManager.getCard(cardID);
            int percent = (int) (joinMember * 100 / card.getMoney());

            if (percent >= 100) {
                percent = 100;
            }

            JsonCrazy crazy = new JsonCrazy();
            crazy.setCardID(cardID);
            crazy.setMoney(card.getMoney());
            crazy.setProgress(percent);
            crazy.setStation(station);
            crazy.setPhase(maxPhase);
            crazy.setNumber(joinMember);

            list.add(crazy);
        }

        RemoteUtil.response(response, list, 1, "返回成功");
    }

    // 历史卡号
    public void historyCard(HttpServletRequest request, HttpServletResponse response) {
        String phase = request.getParameter("phase");
        /**
         * 返回卡和中奖者
         */
        CrazyCompetition competition = crazyManager.getCompetition(Integer.parseInt(phase));

        String cardIDs = competition.getGiftCardID();
        String userIDs = competition.getWinnersID();

        String[] cardIDArr = cardIDs.split(";");
        String[] userIDArr = userIDs.split(";");

        List<JsonCrazyCard> list = new ArrayList<JsonCrazyCard>();
        for (int i = 0; i < cardIDArr.length; i++) {
            int cardID = Integer.parseInt(cardIDArr[i]);
            int winnerID = Integer.parseInt(userIDArr[i]);

            JsonCrazyCard jCard = new JsonCrazyCard();

            jCard.setPhase(Integer.parseInt(phase));
            jCard.setCardID(cardID);
            jCard.setLuckyNumber(winnerID);

            WalletGiftCard card = crazyManager.getCard(cardID);
            // 礼品卡面值
            jCard.setMoney(card.getMoney());
            CrazyCompetitionMember winner = crazyManager.getCompetitionMember(winnerID);

            int time = 0;
            List<CrazyCompetitionMember> member = crazyManager.getOneCompetitionMember(cardID, winner.getUserID());
            for (CrazyCompetitionMember cc1 : member) {
                time += cc1.getChance();
            }
            // 目前只做一次
            jCard.setParticipateTime(time);
            // 0:表示已经结束
            jCard.setStation(1);
            // 手机号
            jCard.setWinnerPhone(winner.getUserPhone());

            ClientInfo info = accountManager.getInfo(winner.getUserID());
            String photoURL = Path.nginx_server_dir_client + Path.PHOTO + File.separator + info.getPhoto();
            jCard.setWinnerPhoto(photoURL);

            list.add(jCard);
        }
        RemoteUtil.response(response, list, 1, "返回成功");
    }

    // 历史疯抢
    public void historyCardMember(HttpServletRequest request, HttpServletResponse response) {
        String phase = request.getParameter("phase");
        String cardID = request.getParameter("giftCardID");
        List<?> list = crazyManager.getCompetitionMemberWithPhoto(Integer.parseInt(phase), Integer.parseInt(cardID));
        List<CompetitionMember> returnlist = CrazyCompetitionMemberParse.memberListParse(list);
        RemoteUtil.response(response, returnlist, 1, "返回成功");
    }

}
